package com.cloud.dataway.config.datasource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@MapperScan("com.cloud.dataway.mapper")
@Configuration
public class DatasourceConf {

    @Bean("dataSource_master")
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource dataSource_master(){
        return DruidDataSourceBuilder.create().build();
    }
    @Bean("dataSource_slave")
    @ConfigurationProperties("spring.datasource.druid.slave")
    public DataSource dataSource_slave(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean("swappedDataSource")
    public DynamicDataSource swappedDataSource(@Qualifier("dataSource_master") DataSource master,
                                               @Qualifier("dataSource_slave") DataSource slave) {

        DynamicDataSource dynamicDataSource = new DynamicDataSource();

        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DbContextHolder.DataSource.MASTER.getText(), master);
        targetDataSources.put(DbContextHolder.DataSource.SLAVE.getText(), slave);
        dynamicDataSource.setTargetDataSources(targetDataSources);

        dynamicDataSource.setDefaultTargetDataSource(master);

        return dynamicDataSource;
    }

    @Bean("dbRoutingInterceptor")
    public DBRoutingInterceptor dbRoutingInterceptor() {
        return new DBRoutingInterceptor();
    }
    @Bean
    public BeanNameAutoProxyCreator beanNameAutoProxyCreator() {
        BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
        beanNameAutoProxyCreator.setBeanNames("*DAO", "*Dao", "*Mapper");
        beanNameAutoProxyCreator.setInterceptorNames("dbRoutingInterceptor");
        beanNameAutoProxyCreator.setProxyTargetClass(true);
        return beanNameAutoProxyCreator;
    }

    @Bean
    public DataSourceTransactionManager transactionManager(@Qualifier("swappedDataSource") DataSource swappedDataSource) {
        return new DataSourceTransactionManager(swappedDataSource);
    }
}
